package com.tarena.lbs.coupon.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tarena.lbs.coupon.base.constant.CouponRedisKey;
import com.tarena.lbs.coupon.dao.mapper.CouponMapper;
import com.tarena.lbs.coupon.dao.mapper.StockMapper;
import com.tarena.lbs.coupon.dao.repository.StockRepository;
import com.tarena.lbs.coupon.base.enums.CouponStatusEnum;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.param.CouponStockRedisParam;
import com.tarena.lbs.coupon.pojo.po.CouponStockPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZHC
 */
@Repository
@Slf4j
public class StockRepositoryImpl implements StockRepository {
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CouponMapper couponMapper;

    @Override
    public void insertCouponStock(Integer couponId, CouponParam couponParam) {
        log.info("CouponStock数据层:新增优惠券库存:{}",couponId);
        // 新增优惠券库存
        CouponStockPO couponStockPO = new CouponStockPO();
        couponStockPO.setCouponId(couponId);
        couponStockPO.setBusinessId(couponParam.getBusinessId());
        couponStockPO.setNum(couponParam.getMaxUsageLimit());
        Date date = new Date();
        couponStockPO.setCreateAt(date);
        couponStockPO.setUpdateAt(date);
        stockMapper.insert(couponStockPO);
    }

    @Override
    public void insertCouponStockInRedis(Integer couponId,CouponParam couponParam) {
        log.info("CouponStock数据层:新增优惠券Redis库存:{}",couponParam);
        // 新增优惠券Redis库存
        // key: coupon:stock:{couponId}
        // value: 优惠券信息对象 CouponStockRedisVO: CouponStock表中的num、Coupon表中的status,enable_status
        // {num, status, enable_status}
        String key = CouponRedisKey.COUPON_STOCK_KEY + couponParam.getId();
        // 查询优惠券库存,设置优惠券redis库存
        QueryWrapper<CouponStockPO> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("coupon_id",couponId);
        CouponStockPO couponStockPO = stockMapper.selectOne(queryWrapper);
        // 检查并清理已存在的冲突key
        try {
            String keyType = redisTemplate.type(key).code();
            if (keyType != null && !"none".equals(keyType) && !"hash".equals(keyType)) {
                redisTemplate.delete(key);
            }
        } catch (Exception e) {
            log.warn("检查Redis key类型时发生异常，强制删除key: {}", key, e);
            redisTemplate.delete(key);
        }
        // 使用Hash存储value提高性能
        Map<String, Object> stockData = new HashMap<>();
        stockData.put("num", couponStockPO.getNum());
        stockData.put("status", CouponStatusEnum.STATUS_ACTIVATE.getCode());
        stockData.put("enable_status", CouponStatusEnum.ENABLE_STATUS_UNUSED.getCode());
        redisTemplate.opsForHash().putAll(key, stockData);
    }

    @Override
    public void updateCouponStock(Integer couponId) {
        log.info("CouponStock数据层:修改优惠券库存:{}",couponId);
        // 修改优惠券库存
        UpdateWrapper<CouponStockPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("num=num-"+1);
        updateWrapper.eq("coupon_id",couponId);
        stockMapper.update(updateWrapper);
    }

    @Override
    public void updateCouponStockInRedis(Integer couponId) {
        log.debug("CouponStock数据层:修改优惠券Redis库存:{}",couponId);
        String key = CouponRedisKey.COUPON_STOCK_KEY + couponId;
        // 扣除优惠券Redis库存，原子性减
        redisTemplate.opsForHash().increment(key, "num", -1);
    }

}
